package br.com.extrajudicial.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Hibernate;
import br.com.caelum.vraptor.view.Results;
import br.com.extrajudicial.dao.OrderDao;
import br.com.extrajudicial.interceptors.RequireUser;
import br.com.extrajudicial.models.Order;

@Resource
public class OrdersController {
	
	@Autowired private OrderDao orderDao;
	@Autowired private Result result;
	@Autowired private Validator validator;
	
	@Get @Path("/orders")
	@RequireUser
	public List<Order> orders() {
		return this.orderDao.listCurrentUserOrders();
	}
	
	@Get @Path("/orders/{id}")
	@RequireUser
	public Order view(Long id) {
		return this.orderDao.load(id);
	}
	
	@Get @Path("/orders/{id}/edit")
	@RequireUser
	public Order edit(Long id) {
		return this.orderDao.load(id);
	}
	
	@Put @Path("/orders")
	@RequireUser
	public void update(Order order) {
		this.validator.addAll(Hibernate.validate(order));
		this.validator.onErrorUse(Results.page()).of(OrdersController.class).edit(order.getId());
		this.orderDao.update(order);
		this.result.redirectTo(OrdersController.class).view(order.getId());
	}
	
	@Delete @Path("/orders/{id}")
	@RequireUser
	public void remove(Long id) {
		Order order = this.orderDao.load(id);
		this.orderDao.delete(order);
		this.result.redirectTo(OrdersController.class).orders();
	}
	
}
